<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script th:inline="javascript">
	(function () {
		var formObj_[(${formName})]_[(${fieldName})] = o("[(${formName})]");
		var nestTableRowId = "[(${nestTableRowId})]";
		var nestFieldName = "[(${nestFieldName})]";

		[# th:each="field : ${fields}"]
		var isShow = [(${isShow})];
		var editable = [(${editable})];
		function initCheckChange_[(${formName})]_[(${fieldName})]_[(${field.name})]() {
			if (!isShow && editable) {
				// var curFormId = getCurFormUtil().get();
				var curFormId = '[(${formName})]';

				var oldValue_[(${field.name})] = "cws-65536"; // 一个不存在的值
				var fName = "[(${field.name})]";
				if (fo(fName, curFormId)) { // 防止此控件也是SQL控件，并且此时还不存在
					oldValue_[(${field.name})] = fo(fName, curFormId).value;
				}

				var sint = setInterval(async function() {
					// 当被缓存时，切换选项卡，o(curFormId)会为null，故不能判断其为null时就清除interval，否则切换回时就无法响应了，
					// 而当点击刷新按钮后，fo(fName, curFormId) 会变为null，此时可以清除interval
					if (o(curFormId)) {
						if (fo(fName, curFormId)) {
							if (oldValue_[(${field.name})] != fo(fName, curFormId).value) {
								console.log('setInterval fName', fName, 'curFormId', curFormId, 'changed value:', fo(fName, curFormId).value);
								oldValue_[(${field.name})] = fo(fName, curFormId).value;
								await onSQLCtlRelateFieldChange_[(${formName})]_[(${fieldName})]();
							}
						} else {
							// 使关闭抽屉时，能够销毁setInterval，否则仅管前端removeScript了，但检测代码仍会运行。如进入编辑页后，再进入详情页，当存在多个SQL宏控件时，检测代码仍会生效，致生成控件
							window.clearInterval(sint);
							console.warn('macro_js_sql_ctl clearInterval [(${field.name})]');
						}
					}
				}, 500);
				// 当菜单项不启用缓存时，只能通过如下方法才能清除interval
				getCurFormUtil().addInterval(sint, '[(${formName})]');
			}
		}

		initCheckChange_[(${formName})]_[(${fieldName})]_[(${field.name})]();
		console.log('initCheckChange_[(${formName})]_[(${fieldName})]_[(${field.name})]()');
		[/]

		// 取得本表单或父表单中相应的值
		function getPFieldVal_[(${formName})]_[(${fieldName})](fieldName) {
			// console.log('getPFieldVal findObj ' + fieldName, 'value:', findObj(fieldName).value);
			if (findObj(fieldName, '[(${formName})]')) {
				// 如果fieldName字段不可写，则其value值为undefined，需从cws_span_中获取
				if (findObj(fieldName, '[(${formName})]').value != undefined) {
					console.log('getPFieldVal formName', '[(${formName})]', fieldName, 'value=', findObj(fieldName, '[(${formName})]').value);
					return findObj(fieldName, '[(${formName})]').value;
				} else if (findObj('cws_span_' + fieldName, '[(${formName})]')) {
					return findObj('cws_span_' + fieldName, '[(${formName})]').innerText;
				}
			} else {
				// 在嵌套表格2中，取主表中的字段（排除查询条件form中的同名字段）
				if ($('form:not([id^="custom"])').find('[name=' + fieldName + ']')[0]) {
					return $('form:not([id^="custom"])').find('[name=' + fieldName + ']').val();
				}
				console.warn('getPFieldVal: ' + fieldName + ' is not exist.');
			}
		}

		async function onSQLCtlRelateFieldChange_[(${formName})]_[(${fieldName})]() {
			var ajaxData = {
				flowId: "[(${flowId})]",
				mainId: "[(${mainId})]",
				fieldName: "[(${fieldName})]",
				isHidden: "[(${isHidden})]",
				editable: "[(${editable})]",
				pageType: "[(${pageType})]",
				[(${fieldPairs})]
				formCode: "[(${formCode})]",
				moduleCode: "[(${moduleCode})]"
			}

			var curFieldName = "[(${fieldName})]";
			/*if (curFieldName.indexOf('sshy') != -1 && curFieldName.indexOf('_rd')==-1) {
				console.log('onSQLCtlRelateFieldChange [(${fieldName})] ajaxData', ajaxData);
			}*/

			console.log('ajaxPost', ajaxPost);
			if (typeof(ajaxPost) != 'function') {
				console.warn('onSQLCtlRelateFieldChange can not be launch. Application is running in back mode, the function ajaxPost is not found.');
				return;
			}

			var data;
			try {
				/*if (typeof showSpinning == 'function') {
					showSpinning(true);
				}*/
				data = await ajaxPost('/flow/macro/onSqlCtlChange', ajaxData);
			} finally {
				/*if (typeof showSpinning == 'function') {
					showSpinning(false);
				}*/
			}

			var formObj = formObj_[(${formName})]_[(${fieldName})];
			if (data.ret == "1") {
				var obj;
				var realFieldName = '';
				console.log('nestFieldName', nestFieldName, 'nestTableRowId', nestTableRowId, 'curFieldName', curFieldName);
				if (nestFieldName == '') {
					obj = findObjInFormObj(formObj, '[(${fieldName})]');
				} else {
					// 来自于嵌套表格 nest_field_nbcbmx_ywlx_0
					realFieldName = 'nest_field_' + nestFieldName + '_[(${fieldName})]_' + nestTableRowId;
					obj = findObjInFormObj(formObj, realFieldName);
				}
				console.log('realFieldName', realFieldName);
				if (obj) {
					// $("#[(${fieldName})]").parent().replaceWith(data.html);	// 似乎无效
					// $("#[(${fieldName})]").prop("outerHTML", data.html);	// 不能仅替换控件本身，因为控件外面包裹了父节点span，需一起清除掉，否则当为必填项时会有两个*
					var $parent = $(obj).parent();

					// $(obj).remove();
					// delete $(obj);
					obj.remove();

					if (nestFieldName == '') {
						$parent.prop("outerHTML", data.html);
					} else {
						var html = data.html.replaceAll(curFieldName, realFieldName);
						$parent.prop("outerHTML", html);
						$('#' + realFieldName).css('width', '96%');
					}

					// 记录当前值
					var curVal;
					// 如果当前该字段被映射，则取映射的值
					if (typeof getModuleFieldMappedValue == 'function') {
						curVal = getModuleFieldMappedValue(obj.name);
					}
					if (curVal == null) {
						curVal = $(obj).val();
					}
					/*if (curFieldName.indexOf('sshy') != -1 && curFieldName.indexOf('_rd')==-1) {
						console.log('onSQLCtlRelateFieldChange [(${fieldName})] ajaxPost curVal=', curVal, 'result data=', data);
					}*/

					// var frm = o("[(${formName})]");
					// var frm = formObj;
					// if (frm) {
						initFormCtl('[(${formName})]');
					// }
					// initFormCtl在前端utils/util.ts中定义
					/*if (getCurForm()) {
						initFormCtl(getCurForm().id);
					} else if (o('customForm')) {
						// 模块列表中的查询条件表单
						initFormCtl('customForm');
					} else if (o('customFormChildren')) {
						// 关联模块列表中的查询条件表单
						initFormCtl('customFormChildren');
					} else {
						console.error('SQL宏控件未找到表单，无法对控件样式初始化');
					}*/

					console.log('realFieldName', realFieldName, 'curVal', curVal);
					// 20230322 当为select时需赋值，因多级联动时生成的控件为select型，否则会因为未赋予curVal，致值为空
					// 20230326 当为INPUT时(即表单域选择宏控件映射时，如报签约时选择项目映射产业类型)不能赋值curVal，否则会导致联动时，第二级始终因被赋值而检测不到变化，致第三级不会发生变化
					// if (true || data.type == "select") {
					if (data.type == "select") {
						// 注意上面prop("outerHTML")操作后，原来的obj仍存在，会导致赋值无效，故需重新findObj
						// $(fo('[(${fieldName})]', '[(${formName})]')).val(curVal);
						if (nestFieldName == '') {
							$(findObjInFormObj(formObj, '[(${fieldName})]')).val(curVal);
						} else {
							$('#' + realFieldName).val(curVal);
						}
					}

					var isList = [(${isList})];
					// 如果为列表页面，不需要验证
					if(!isList) {
						try {
							// 删除原来的验证，否则会因为原验证中存储的对象不存在而导致验证失效
							var frmObj = LiveValidationForm.getInstance(formObj);
							if (frmObj) {
								frmObj.removeFieldByName('[(${fieldName})]');
							}
							[(${checkFieldJs})]
						} catch (e) {
							// 防止ureport查询条件中调用时，因无LiveValidationForm对象页报错
							console.warn(e);
						}
					}
				}

				try {
					initCalculator();
				}
				catch(e) {}
				try {
					// 重新绑定显示规则
					doViewJS_[(${formName})]();
				} catch (e) {}
			}
		}

		var isShow = [(${isShow})];
		var editable = [(${editable})];
		// nest_sheet_edit_relat.jsp中传过来时是edit
		// initCheckChange_中初始化时已调用过onSQLCtlRelateFieldChange_了，此处不需要重复执行，但是去掉了，只读状态也会丢失
		if (!isShow && editable) {
			onSQLCtlRelateFieldChange_[(${formName})]_[(${fieldName})]();
		}

	})();
</script>
</body>
</html>